﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kaidou.Util;
using System.Net;
using System.Net.Mail;
using System.IO;

namespace Kaidou.Bll
{
    public class MailSendManager
    {
     
        /**
	     * メールを送信します。
	     */
        public static void sendMail(Mail mail, string RootPath)
        {
            try
            {
                string framework_mail_default_messageid = null;
                string framework_mail_default_messagepw = null;

                try
                {
                    StreamReader objReader = new StreamReader(RootPath + "\\email.txt");
                    string a = objReader.ReadLine();
                    string b = objReader.ReadLine();
                    string c = objReader.ReadLine();
                    string d = objReader.ReadLine();
                    objReader.Close();

                    string[] a1 = a.Split('=');
                    string[] b1 = b.Split('=');
                    string[] c1 = c.Split('=');
                    string[] d1 = d.Split('=');

                    framework_mail_default_messageid = b1[1];
                    framework_mail_default_messagepw = c1[1];

                    LogManager.info("==============================framework_mail_default_messageid==" + framework_mail_default_messageid);
                    LogManager.info("==============================framework_mail_default_messagepw==" + framework_mail_default_messagepw);


                }
                catch (Exception e2)
                {
                    framework_mail_default_messageid = "";
                    framework_mail_default_messagepw = "";
                }

                mail = createMail(mail, RootPath);
                Encoding encode = Encoding.GetEncoding("utf-8");

                SmtpClient smtp = new SmtpClient(); 
                smtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
                smtp.EnableSsl = false;
                smtp.Host = mail.getSmtpHostName(); 
                smtp.Port = 25;            
                smtp.UseDefaultCredentials = true;
                smtp.Credentials = new NetworkCredential(framework_mail_default_messageid, framework_mail_default_messagepw);
                MailMessage mm = new MailMessage(); 
                //mm.Priority = MailPriority.High; 
                mm.From = new MailAddress(mail.getFrom(), mail.getFrom(), encode);

                // 宛先 (To) をセット
                for (int i = 0; i < mail.getToList().Length; i++)
                {
                    mm.To.Add(new MailAddress(mail.getTo(i), mail.getTo(i), encode));
                }

                // 宛先 (CC) をセット
                if (mail.getCcList() != null)
                {
                    for (int i = 0; i < mail.getCcList().Length; i++)
                    {
                        mm.CC.Add(new MailAddress(mail.getCc(i), mail.getCc(i), encode));
                    }

                }
                // 宛先 (BCC) をセット
                if (mail.getBccList() != null)
                {
                    for (int i = 0; i < mail.getBccList().Length; i++)
                    {
                        mm.Bcc.Add(new MailAddress(mail.getBcc(i), mail.getBcc(i), encode));
                    }

                }

                // 件名 (Subject) をセット
                if (mail.getSubject() != null)
                {
                    mm.Subject = mail.getSubject();// EncodeMailHeader(mail.getSubject(), encode);
                }

                // 本文をセット
                if (mail.getMessage() != null && mail.getFileNameList() == null)
                {
                    mm.Body = mail.getMessage();
                }

                mm.SubjectEncoding = Encoding.GetEncoding("utf-8");

                mm.IsBodyHtml = false; 

                mm.BodyEncoding = encode;

                smtp.Send(mm); 

            }catch(Exception mailex){
                LogManager.error("send mail fail!!!"+mailex.Message);
                throw new Exception("send mail fail!!!" + mailex.Message);
            }
        }

        private string EncodeMailHeader(string str, Encoding enc)
        {

            string ret = System.Convert.ToBase64String(enc.GetBytes(str));
            ret = string.Format("=?{0}?B?{1}?=", enc.BodyName, ret);
            return ret;
        }

        /**
	     * 設定ファイル (mailservice.propertiyes のデフォルト値) を利用して、メール情報を構築します
	     *
	     * @param	mail	送信するメール情報
	     * @return	Mail	<b>not null:</b> 送信するメール情報、<b>null:</b> 異常発生
	     */
        private static Mail createMail(Mail mail ,string RootPath)
        {
            
            string framework_mail_default_from = null;
            string framework_mail_default_smtpserver = null;

            try
            {
                StreamReader objReader = new StreamReader(RootPath + "\\email.txt");
                string a = objReader.ReadLine();
                string b = objReader.ReadLine();
                string c = objReader.ReadLine();
                string d = objReader.ReadLine();
                objReader.Close();

                string[] a1 = a.Split('=');
                string[] b1 = b.Split('=');
                string[] c1 = c.Split('=');
                string[] d1 = d.Split('=');

                framework_mail_default_from = a1[1];
                framework_mail_default_smtpserver = d1[1];

                LogManager.info("==============================framework_mail_default_from==" + framework_mail_default_from);

                LogManager.info("==============================framework_mail_default_smtpserver==" + framework_mail_default_smtpserver);

               
            }
            catch (Exception e2)
            {
                framework_mail_default_from = "";
                framework_mail_default_smtpserver = "";
            }

		//--------------------------------
		// 優先度をセット
		//if (mail.getPriority() == null)
		//	mail.setPriority("3");
		//--------------------------------
		// 送信者をセット
		if (mail.getFrom() == null)
            mail.setFrom(framework_mail_default_from);
		//--------------------------------
		// SMTP サーバー名をセット
		if (mail.getSmtpHostName() == null)
            mail.setSmtpHostName(framework_mail_default_smtpserver);
		//--------------------------------
		// 文字コードをセット
		if (mail.getCharSet() == null)
            mail.setCharSet("iso-2022-jp");

		//-------------------------------
		// メール情報のチェック
		if (mail.getSmtpHostName() == null) {
			//throw new MailSendFailedException("SMTP Server name is null");
            LogManager.error("SMTP Server name is null");
		}
		
		if (mail.getPriority() == null) {
			//throw new MailSendFailedException("Priority is null");
            LogManager.error("Priority is null");
		}
            /*
		if (rm.GetString("framework_mail_default_xmailer") == null) {
			//throw new MailSendFailedException("X-Mailer is null");
            LogManager.error("X-Mailer is null");
		}
           */
		if (mail.getFrom() == null) {
			//throw new MailSendFailedException("From is null");
            LogManager.error("From is null");
		}
		if (mail.getToList() == null) {
            //throw new MailSendFailedException("To list is null");
            LogManager.error("To list is null");
		}
		return mail;
	}


    }
}
